package com.itheima.aspect;

import com.itheima.service.EquipmentService;
import com.itheima.service.OrderService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

//设置该类为切面类
@Component
@Aspect
public class MyAdvice {

    //定义切入点  (对EquipmentServiceImpl类的添加方法进行增强)
    @Pointcut("execution(void com.itheima.service.impl.EquipmentServiceImpl.add*(..))")
    public void pt() {
    }

    //使用环绕通知增强方法
    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) {
        Object o = null;
        try {
            //获取当前方法的参数     Equipment equipment
            Object[] args = pjp.getArgs();
            if (args.length>0){
                for (Object arg : args) {
                    //使用反射获取当前参数的属性值
                    Class<?> clazz = arg.getClass();
                    Field created = clazz.getDeclaredField("created");
                    Field updated = clazz.getDeclaredField("updated");
                    //暴力反射赋值
                    created.setAccessible(true);
                    updated.setAccessible(true);
                    //如果没有设置值，就给它设置值
                    if (created.get(arg)==null){
                        created.set(arg,new Date());
                    }
                    if(updated.get(arg)==null){
                        updated.set(arg,new Date());
                    }
                }
            }
            //执行原来方法
            o = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }

}
